package com.walle.concurrenttest.pattern.workthread;

import java.util.LinkedList;

/**
 * @author zhangjiapeng
 * @Package com.walle.concurrenttest.pattern.workthread
 * @Description: ${todo}
 * @date 2019/2/22 10:27
 */
public class Channel {

    private static final  int MAX_REQUEST = 100;

    private final LinkedList<Thread> requestQueue;

    private LinkedList<Request> requests;

    public Channel(int threadCount) {
        this.requestQueue = new LinkedList();
        this.requests = new LinkedList();
        for (int i = 0; i < threadCount; i++) {
            Thread workerThread = new WorkerThread("worker" + i,this);
            requestQueue.addLast(workerThread);
        }
    }

    public void startWorkers(){
        for (int i = 0; i < requestQueue.size(); i++) {
            requestQueue.get(i).start();
        }
    }

    public synchronized void putRequest(Request request){
        while (requests.size() >= MAX_REQUEST){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        requests.addFirst(request);
        this.notifyAll();

    }


    public synchronized Request takeRequest(){
        while (requests.size() <=0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Request request = requests.removeLast();
        this.notifyAll();
        return  request;
    }

}
